package org.jash.shop2202.goods

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import org.jash.shop2202.entity.Goods
import org.jash.shop2202.mvvm.BaseViewModel
import org.jash.shop2202.net.ApiService
import javax.inject.Inject
import kotlin.reflect.KFunction

@HiltViewModel
class DetailViewModel @Inject constructor(val service:ApiService):BaseViewModel() {
    val goodsLiveData by lazy { MutableLiveData<Goods>() }
    val addCartLiveData by lazy { MutableLiveData<String>() }
    fun loadDetail(id:Int) {
        viewModelScope.launch {
            try {
                val res = service.getDetail(id)
                if (res.code == 200) {
                    goodsLiveData.postValue(res.data)
                } else {
                    failureLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }
    }
    fun addCart(id:Int) {
        viewModelScope.launch {
            try {
                val res = service.addCart(mapOf("goods_id" to id.toString(), "count" to "1"))
                if (res.code == 200) {
                    addCartLiveData.postValue(res.message)
                } else {
                    failureLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }
    }
}